<template>
	<div class="page-box" style="position: relative;overflow-x: hidden;">
	<t-sticky :style="{ backgroundColor: '#fff' }">
	
	<div class="custom-header-box">
		<div class="back" @click="goBack">
			<icon-font name="chevron-left" size="32px"/>
		</div>
		<div class="search-box">
				<t-search v-model="searchValue" :clearable="true" :style="{ width: 'calc(100% - 64px)',height:'40px',fontSize:'16px' }" shape="round" placeholder="请输入关键字" ></t-search>
				<div class="search-btn" @click="handleSearch">
					<p>搜索</p>
				</div>
		</div>
	</div>
	<div class="history-box" >
		<div class="history-item">
			<!-- <up-tag class="item" v-for="(item, index) in searchHistory" :key="index" :text="item" size="mini"
				bgColor="#f5f5f5" borderColor="#f5f5f5" color="#6C6C6C" textSize="24rpx"
				@click="clickHistory(item)"></up-tag> -->
				<t-tag v-for="(item, index) in searchHistory" :key="index" variant="light" @click="clickHistory(item)" style="margin-right:10px;font-size: 14px;margin-bottom: 10px;">{{item}}</t-tag>
		</div>
	</div>

	<!-- <div class="tabs-box">
		<div :class="['tabs-item', tabsIndex === 0 && 'tabs-item-active']" @click="handleTabs({index:0})">
			漫画
		</div>
		<div :class="['tabs-item', tabsIndex === 1 && 'tabs-item-active']" @click="handleTabs({index:1})">
			广场
		</div>
	</div> -->
	</t-sticky>
	<!-- <scroll-view scroll-y class="scroll"> -->
	<div class="scroll">
		<!-- 显示漫画列表 -->
		<div class="comic-list" v-show="tabsIndex === 0">
			<div style="width: 100vw; text-align: center; font-size: 28rpx; color: #ccc; margin-top: 35rpx;" v-if="comic_dataList.length < 1">暂无搜索数据</div>
			<div class="itembox" v-for="(item,index) in comic_dataList" :key="index"
				@click="goToBookDetail(item.course?.courseId)">
				<!-- <image :src="item.course?.titleImg" mode="aspectFill" class="img"></image> -->
				<!-- <up-lazy-load :image="item?.course?.titleImg" mode="widthFix" class="cimg"
					style="border-radius: 12rpx;"></up-lazy-load> -->
					<!-- <t-image
					  class="target-image"
					  :src="item?.course?.titleImg"
					  shape="round"
					  :style="{width: '55px',height: '75px',borderRadius:'6px'}"
					  fit="cover"
					></t-image> -->
				<div class="img-box">
					<ImageCache :url="item?.course?.titleImg" :record="item"></ImageCache>
				</div>
				<div class="infobox">
					<text class="title">{{item.course?.title}}</text>
					<text class="type">{{item.course?.classify}}</text>
					<div class="hot-box">
						<text
							class="hot">{{item?.course?.viewCounts}}{{item?.course?.viewCounts >= 10000 ? "万人": "人"}}阅读</text>
					</div>
				</div>
				<!-- <div class="action">
					<up-icon name="heart" color="#999" style="font-weight: 900" size="28" @click="collect"></up-icon>
				</div> -->
			</div>
			<!-- <p  status="nomore" line nomoreText="啊呀~到底了呢" color="#b9b9b9" lineColor="#b9b9b9"
				fontSize="11" >啊呀~到底了呢 </p> -->
			<div class="tishi" v-if="comic_dataList?.length > 0">
				<span></span>
				<p>啊呀~到底了呢</p>
				<span></span>
			</div>
		</div>

		<!-- 显示广场列表 -->
		<div class="square-list" v-show="tabsIndex === 1">
			<div style="width: 100vw; text-align: center; font-size: 28rpx; color: #ccc; margin-top: 35rpx;" v-if="square_dataList.length < 1">暂无搜索数据</div>
			<div class="itembox" v-for="(item,index) in square_dataList" :key="index"
				@click="goToSquareDetail(item.photobookId)">
				<!-- <image :src="item.course?.titleImg" mode="aspectFill" class="img"></image> -->
				<!-- <up-lazy-load :image="item.photo?.titleImg" mode="aspectFill" class="img"
					style="border-radius: 12rpx;"></up-lazy-load> -->
					<t-image
					  class="target-image"
					  :src="item.photo?.titleImg"
					  shape="round"
					  :style="{width: '75px',height: '75px',borderRadius:'6px'}"
					  fit="cover"
					></t-image>
				<div class="infobox">
					<text class="title">{{item.photo?.title}}</text>
					<text class="type">{{item.photo?.authorName}}</text>
				</div>
				<!-- <div class="action">
					<up-icon name="heart" color="#999" style="font-weight: 900" size="28" @click="collect"></up-icon>
				</div> -->
			</div>
			<!-- <up-loadmore v-if="square_dataList?.length > 0" status="nomore" line nomoreText="啊呀~到底了呢" color="#b9b9b9" lineColor="#b9b9b9"
				fontSize="11" /> -->
				<div class="tishi" v-if="square_dataList?.length > 0">
					<span></span>
					<p>啊呀~到底了呢</p>
					<span></span>
				</div>
		</div>
	<!-- </scroll-view> -->
	 </div>
	</div>
</template>

<script setup>
	import {
		ref
	} from "vue";
	import {
		useRouter,
		useRoute
	} from 'vue-router';
	import {
		maxTenThousand
	} from "@/utils/utils.js"
	import comicApi from "@/api/comicApi";
	import squareApi from "@/api/squareApi";
	import {
		debounce
	} from 'lodash';
	import searchApi from "@/api/searchApi";
	import { IconFont } from 'tdesign-icons-vue-next';
	import { Toast } from 'tdesign-mobile-vue';
	import ImageCache from "@/components/ImageCache";

	const router = useRouter();
	const route = useRoute();
	const comic_dataList = ref([]);
	const square_dataList = ref([]);
	const searchValue = ref("");
	// const searchHistory = ref(uni.getStorageSync("searchHistory") ? JSON?.parse(uni.getStorageSync("searchHistory")) : []);
	
	
	function getStorageSync(key) {
	  const data = localStorage.getItem(key);
	  return data ? data : null;
	}
	
	const searchHistory = ref(
	  getStorageSync("searchHistory") 
	    ? JSON.parse(getStorageSync("searchHistory")) 
	    : []
	);


	// 搜索按钮样式
	const actionStyle = ref({
		borderRadius: "100rpx",
		padding: "20rpx",
		background: "linear-gradient(90deg, #FFC151 0%, #FF876F 100%)",
	})

	const tabsList = [{
			name: '漫画',
			index: 0
		},
		{
			name: '广场',
			index: 1
		}
	];
	const tabsIndex = ref(0);

	// 切换tab
	const handleTabs = (item) => {
		tabsIndex.value = item.index;
	}

	// 回退
	const goBack = () => {
		router.back();
	}

	// 点击历史记录
	const clickHistory = (item) => {
		searchValue.value = item;
	}

	// 打开漫画
	const goToBookDetail = debounce((courseId) => {
		// uni.navigateTo({
		// 	url: `/pages/comic/details?courseId=${courseId}`
		// })
		router.push({
			name: 'home',
			query: {
				courseId: courseId
			}
		});
	}, 300);

	// 打开广场
	const goToSquareDetail = debounce((photobookId) => {
		// uni.navigateTo({
		// 	url: `/pages/square/details?photobookId=${photobookId}`
		// })
	}, 300);

	// 查询漫画
	const getComic = async (params) => {
		comic_dataList.value = [];
		params.keyword = encodeURIComponent(params.keyword);
		const result = await searchApi.globalSearch(params);
		if(result.code === 0){
			comic_dataList.value = result.data;
		}else{
			comic_dataList.value = [];
		}
	}


	// 查询广场
	const getSquare = async (params) => {
		params.keyword = encodeURIComponent(params.keyword);
		const result = await searchApi.globalSearch(params);
		if(result.code === 0){
			square_dataList.value = result.data;
		}else{
			square_dataList.value = [];
		}
		
	}

	//  搜索数据
	const handleSearch = async (value) => {
		if(searchValue.value == ''){
			Toast({
			    duration: 2000,
			    message: '搜索框不能为空',
			});
			return false
		}
		if (value) {
			await getComic({
				keyword: searchValue.value,
				type: "course"
			});
			await getSquare({
				keyword: searchValue.value,
				type: "photobook"
			});
			saveSearchHistory();
		}
	}

	// 保存搜索记录
	const saveSearchHistory = () => {
	    if (!searchHistory.value.includes(searchValue.value)) {
	        // 创建新数组：添加新值 + 反转历史记录
	        let newHistory = [...searchHistory.value, searchValue.value].reverse();
	        
	        // 限制最多保存10条
	        if (newHistory.length > 10) {
	            // 移除最早的一条（反转后数组的最后一条）
	            newHistory = newHistory.slice(0, 10);
	        }
	        
	        searchHistory.value = newHistory;
	        localStorage.setItem("searchHistory", JSON.stringify(searchHistory.value));
	    }
	}
</script>

<style lang="scss" scoped>
	.custom-header-box {
		display: flex;
		justify-content: space-between;
		align-items: center;
		height: 50px;
		padding-top: var(--status-bar-height);
		padding-left: 10px;
		padding-right: 10px;
		background: #fff !important;
		// background: transparent;
		overflow: hidden;

		.text {
			font-size: 20px;
			font-weight: 500;
			color: rgb(108, 108, 108);
			flex: 1;
			text-align: center;
			color: #fff;
		}

		.search-box {
			width: calc(100% - 40px);
			margin-left: 10px;
			border-radius: 50px;
			background: rgba(0, 0, 0, 0.05);
			display: flex;
			align-items: center;
			justify-content: space-between;
			.search-btn{
				width: 64px;
				height: 40px;
				border-radius: 20px;
				overflow: hidden;
				background: linear-gradient(90deg, rgb(255, 193, 81) 0%, rgb(255, 135, 111) 100%);
				font-size: 14px;
				color: #303133;
				line-height: 40px;
			}
		}
		.back{
			
		}

	}

	.history-box {
		display: flex;
		padding:10px 13px;
		padding-bottom: 0;
		background-color: #fff;
		border-bottom: 1px solid #e1e1e1;

		.history-item {
			display: flex;
			flex-wrap: wrap;

			.item {
				margin-right: 5px;
				margin-bottom: 5px;
			}
		}
	}

	.tabs-box {
		width: 100%;
		display: flex;
		flex-direction: row;
		background: #fff;
		align-items: center;
		padding: 2.5px 0;
		border-top: 1px solid rgba(0, 0, 0, 0.10);
		border-bottom: 1px solid rgba(0, 0, 0, 0.10);
		background-color: #fff;

		.tabs-item {
			flex: 1;
			display: flex;
			flex-direction: row;
			align-items: center;
			justify-content: center;
			font-size: 16px;
			height: 40px;
			border-bottom: #fff solid 4px;
		}

		.tabs-item-active {
			border-bottom: #F1B444 solid 4px;
		}

	}

	.scroll {
		height: calc(100vh - 150px);
		
		// margin-top: 150px;
		.comic-list {
			display: flex;
			flex-direction: column;
			padding: 13px;

			.itembox {
				display: flex !important;
				margin-bottom: 10px;
				.cimg {
					width: 55px;
					height: 75px;
				
				}
				
				.over{
					position: absolute;
					right: 5px;
					top: -5px;
				}

				

				.infobox {
					display: flex;
					flex: auto;
					flex-direction: column;
					align-items: flex-start;
					justify-content: flex-start;
					margin-left: 10px;
					.title {
						color: #FF5959;
						font-size: 13px;
						font-weight: 700;
					}

					.type {
						color: #999;
						font-size: 12px;
						font-weight: 550;
						margin-top: 10px;
					}

					.hot-box {
						margin-top: 5px;

						.hot {
							padding: 6px 4px;
							color: #AC8920;
							font-size: 12px;
							font-style: normal;
							font-weight: 550;
							border-radius: 3px;
							margin-top: 10px;
							background: rgba(241, 180, 68, 0.15);
						}
					}
				}
			}
		}


		.square-list {
			display: flex;
			flex-direction: column;
			padding: 13px;

			.itembox {
				display: flex;
				flex-direction: row;
				margin-bottom: 0px;
				.img {
					width: 75px;
					height: 75px;
				}

				.infobox {
					display: flex;
					flex: auto;
					flex-direction: column;
					width: calc(100% - 85px);
					margin-left: 10px;
					.title {
						color: #FF5959;
						font-size: 13px;
						font-weight: 700;
						display: -webkit-box;
						  -webkit-line-clamp: 2; /* 显示 3 行 */
						  -webkit-box-orient: vertical;
						  overflow: hidden;
						  text-overflow: ellipsis; /* 溢出时显示省略号 */
					}

					.type {
						color: #999;
						font-size: 12px;
						font-weight: 550;
						margin-top: 10px;
					}

					.hot-box {
						margin-top: 5px;

						.hot {
							padding: 6px 4px;
							color: #AC8920;
							font-size: 12px;
							font-style: normal;
							font-weight: 500;
							border-radius: 3px;
							margin-top: 10px;
							background: rgba(241, 180, 68, 0.15);
						}
					}
				}
			}
		}
	}
	.tishi{
		display: flex;
		align-items: center;
		justify-content: center;
		margin-bottom: 10px;
		// padding-top: 10px;
		span{
			display: inline-block;
			width: 36px;
			height: 1px;
			margin: 0 10px;
			background-color: #b9b9b9;
		}
		p{
			font-size: 12px;
			color: #b9b9b9;
		}
	}
	.img-box{
		width: 55px;
		height: 75px;
		border-radius: 6px;
		overflow: hidden;
	}
</style>